import React from 'react'

class App extends React.Component {
  // 1. 创建 ref 对象,挂载到实例身上
  inputRef = React.createRef()
  state = {
    value: '123',
    textVal: '天气不错',
    selectVal: '1',
    checkval: false
  }
  
  // 简化封装
  formHandler = e => {
    const val = e.target.type === 'checkbox' ? e.target.checked : e.target.value
    this.setState({
      [e.target.name]: val
    })
  }

  refChange = () => {
    // 从实例上直接获取 ref 对象,通过 current 取值
    console.log(this.inputRef.current.value)
  }

  render() {
    return (
      <div>
        {this.state.value}
        <input name="value" onChange={this.formHandler} value={this.state.value} type="text" /> <br/>
        <textarea name="textVal" cols="30" rows="10" value={this.state.textVal} onChange={this.formHandler}>
        </textarea> <br/>
        <select name="selectVal" value={this.state.selectVal} onChange={this.formHandler}>
            <option value={1}>男</option>
            <option value={2}>女</option>
            <option value={3}>模糊</option>
        </select> <br />
        <input name="checkval" type="checkbox" checked={this.state.checkval} onChange={this.formHandler} /><br />
        <input type="text" ref={this.inputRef} onChange={this.refChange} />

      </div>
    );
  }
}

export default App